/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: BookView.java
 *   @Date: 18-11-29 下午4:05
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.view;


import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.support.annotation.Nullable;
import android.support.v4.view.GestureDetectorCompat;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.TypedValue;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;

import io.bhex.app.R;
import io.bhex.app.utils.CommonUtil;
import io.bhex.app.utils.SkinColorUtil;
import io.bhex.app.view.bean.Book;
import io.bhex.baselib.utils.PixelUtils;

/**
 * ================================================
 * 描   述: 盘口挂单记录
 * ================================================
 */

public class BookView extends View {
    //进度左开始绘制模式
    public static final int PROGRESS_LEFT_MODE = 0;
    //进度右开始绘制模式
    public static final int PROGRESS_RIGHT_MODE = 1;
    private static final String TAG = "BookView";
    private Book mBook;
    private float priceSize;
    private float volumeSize;
    private float mProgress;
    private int progressColor;
    private int priceGreenColor;
    private int priceRedColor;
    private int volumeColor;
    private Paint paint;
    private int viewHeight;
    private int viewWidth;
    private int mProgressMode;
    private int DEFAULT_PADDING_RIGHT = 0;
    private int DEFAULT_PADDING_LEFT = 0;
    private float paddingRight;
    private float paddingLeft;
    private float paddingTop;
    private float paddingBottom;
    private final DisplayMetrics mDisplayMetrices = getResources().getDisplayMetrics();
    private int mDefaultWidth = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 250, mDisplayMetrices);

    private int mDefaultHeight = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 24, mDisplayMetrices);
    private GestureDetectorCompat gestureDetectorCompat;
    private OnClickListener mClickLintener;
    private float markedCircleRadius = PixelUtils.dp2px(2);
    private float marginLeftOfMarkedCircle = PixelUtils.dp2px(8);

    public BookView(Context context) {
        this(context, null);
    }

    public BookView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public BookView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);

        init(context, attrs);
    }

    private void init(Context context, AttributeSet attrs) {
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.BookView);
        paddingLeft = typedArray.getDimension(R.styleable.BookView_BV_paddingLeft, 0);
        paddingTop = typedArray.getDimension(R.styleable.BookView_BV_paddingTop, 0);
        paddingRight = typedArray.getDimension(R.styleable.BookView_BV_paddingRight, 0);
        paddingBottom = typedArray.getDimension(R.styleable.BookView_BV_paddingBottom, 0);
        priceSize = typedArray.getDimension(R.styleable.BookView_priceTextSize, getResources().getDimension(R.dimen.font_12));
        volumeSize = typedArray.getDimension(R.styleable.BookView_volumeTextSize, getResources().getDimension(R.dimen.font_12));
        priceGreenColor = typedArray.getColor(R.styleable.BookView_priceTextGreenColor, SkinColorUtil.getDark(this.getContext()));
        priceRedColor = typedArray.getColor(R.styleable.BookView_priceTextRedColor, SkinColorUtil.getDark(this.getContext()));
        volumeColor = typedArray.getColor(R.styleable.BookView_volumeTextColor, CommonUtil.isBlackMode()?getResources().getColor(R.color.dark_night):getResources().getColor(R.color.dark));
        progressColor = typedArray.getColor(R.styleable.BookView_progressColor, getResources().getColor(R.color.red));
        mProgress = typedArray.getFloat(R.styleable.BookView_progressRatio, 0);
        mProgressMode = typedArray.getInt(R.styleable.BookView_progressMode, PROGRESS_LEFT_MODE);
        typedArray.recycle();
        setWillNotDraw(false);
        setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        gestureDetectorCompat = new GestureDetectorCompat(context, new BookViewGestureViewListener());

        paddingRight = DEFAULT_PADDING_RIGHT;
        paddingLeft = DEFAULT_PADDING_LEFT;

        paint = new Paint();
        viewHeight = getHeight();
        viewWidth = getWidth();
    }

    public void setPaddingLeft(float paddingLeft) {
        this.paddingLeft = paddingLeft;
    }

    public void setPaddingRight(float paddingRight) {
        this.paddingRight = paddingRight;
    }

    public void setPaddingTop(float paddingTop) {
        this.paddingTop = paddingTop;
    }

    public void setPaddingBottom(float paddingBottom) {
        this.paddingBottom = paddingBottom;
    }

    /**
     * 设置数据
     *
     * @param book
     */
    public void setBook(Book book) {
        mBook = book;
        if (book.getPriceColor()!=0) {
            if (book.isBid()) {
                priceGreenColor = book.getPriceColor();
            }else{
                priceRedColor = book.getPriceColor();
            }
        }
        if (book.getProgressColor()!=0) {
            progressColor = book.getProgressColor();
        }
        mProgress = book.getProgress();
        mProgressMode = book.getProgressMode();
        invalidate();
    }

    public Book getBook(){
        return mBook;
    }

    /**
     * 设置点击事件
     * @param lintener
     */
    public void setOnClickLintener(OnClickListener lintener){
        mClickLintener = lintener;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int width;
        int height;

        // Get measureSpec mode and size values.
        final int measureWidthMode = MeasureSpec.getMode(widthMeasureSpec);
        final int measureHeightMode = MeasureSpec.getMode(heightMeasureSpec);
        final int measureWidth = MeasureSpec.getSize(widthMeasureSpec);
        final int measureHeight = MeasureSpec.getSize(heightMeasureSpec);

        // The RangeBar width should be as large as possible.
        if (measureWidthMode == MeasureSpec.AT_MOST) {
            width = measureWidth;
        } else if (measureWidthMode == MeasureSpec.EXACTLY) {
            width = measureWidth;
        } else {
            width = mDefaultWidth;
        }

        // The RangeBar height should be as small as possible.
        if (measureHeightMode == MeasureSpec.AT_MOST) {
            height = Math.min(mDefaultHeight, measureHeight);
        } else if (measureHeightMode == MeasureSpec.EXACTLY) {
            height = measureHeight;
        } else {
            height = mDefaultHeight;
        }

        setMeasuredDimension(width, height);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        viewWidth = w;
        viewHeight = h;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        drawProgress(canvas);
        drawPrice(canvas);
        drawVolume(canvas);
        drawMarkedCircle(canvas);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        gestureDetectorCompat.onTouchEvent(event);
        return super.onTouchEvent(event);
    }

    /**
     * 绘制成交量
     *
     * @param canvas
     */
    private void drawVolume(Canvas canvas) {
        if (mBook == null) {
            return;
        }
        paint.setStyle(Paint.Style.FILL);
        paint.setTextSize(volumeSize);
        paint.setFakeBoldText(false);
        paint.setColor(volumeColor);
        if (mBook.isShowCumulativeVolume()) {
            //累计数量
            if (!TextUtils.isEmpty(mBook.getCumulativeVolume())) {
                String volume = mBook.getCumulativeVolume();
                float textViewLenth = paint.measureText(volume);
                canvas.drawText(volume, viewWidth - textViewLenth - paddingRight, viewHeight / 2 + volumeSize / 2, paint);
            }
        }else{
            //单档数量
            if (!TextUtils.isEmpty(mBook.getVolume())) {
                String volume = mBook.getVolume();
                float textViewLenth = paint.measureText(volume);
                canvas.drawText(volume, viewWidth - textViewLenth - paddingRight, viewHeight / 2 + volumeSize / 2, paint);
            }
        }
    }

    /**
     * 绘制价格
     *
     * @param canvas
     */
    private void drawPrice(Canvas canvas) {
        if (mBook == null) {
            return;
        }
        paint.setStyle(Paint.Style.FILL);
        paint.setTextSize(priceSize);
        paint.setFakeBoldText(true);  //加粗字体
        paint.setColor(mBook.getPriceColor()==0 ? (mBook.isBid() ? priceGreenColor : priceRedColor) : mBook.getPriceColor());
        if (!TextUtils.isEmpty(mBook.getPrice())) {
            canvas.drawText(mBook.getPrice(), paddingLeft, viewHeight / 2 + priceSize / 2, paint);
        }

    }

    /**
     * 绘制价格的标记圆
     * @param canvas
     */
    private void drawMarkedCircle(Canvas canvas) {
        if (mBook == null) {
            return;
        }
        if (mBook.isHasOrderMarked()) {
            paint.setAntiAlias(true);
            paint.setColor(mBook.getPriceColor()==0 ? (mBook.isBid() ? priceGreenColor : priceRedColor) : mBook.getPriceColor());
            String price = mBook.getPrice();
            float priceLength = paint.measureText(price);
            if (!TextUtils.isEmpty(mBook.getPrice())) {
                canvas.drawCircle(paddingLeft + priceLength + marginLeftOfMarkedCircle, viewHeight / 2 + markedCircleRadius / 2 ,markedCircleRadius, paint);
            }
        }
    }

    /**
     * 绘制进度条
     *
     * @param canvas
     */
    private void drawProgress(Canvas canvas) {
        paint.setAntiAlias(true);
        paint.setColor(progressColor);
        float l, t, r, b;
        if (mProgressMode == PROGRESS_LEFT_MODE) {
            l = 0;
            r = viewWidth * mProgress;
        } else {
            l = viewWidth * (1 - mProgress);
            r = viewWidth;
        }

        t = 0+paddingTop;
        b = viewHeight-paddingBottom;
//        DebugLog.e(TAG, l + " " + t + " " + r + " " + b + "  mProgress:" + mProgress);
        canvas.drawRect(l, t, r, b, paint);

    }

    /**
     * 设置View的宽高
     * @param w
     * @param h
     */
    public void setViewWH(int w, int h) {
        mDefaultWidth = w;
        mDefaultHeight = h;
    }

    class BookViewGestureViewListener extends GestureDetector.SimpleOnGestureListener {
        @Override
        public boolean onDown(MotionEvent e) {
//            if (mBook != null) {
//                ToastUtils.showShort(mBook.getPrice()+" "+mBook.getVolume());
//            }else{
//                ToastUtils.showShort("null");
//            }
            if (mClickLintener != null) {
                mClickLintener.onClick(mBook);
            }
            return true;
        }
    }

    public interface OnClickListener{
        void onClick(Book book);
    }

}
